package com.yao2san.simdif.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yao2san.common.exception.BusiException;
import com.yao2san.simdif.bean.request.*;
import com.yao2san.simdif.bean.response.DatasourceListRes;
import com.yao2san.simdif.entity.ColumnInfo;
import com.yao2san.simdif.entity.Datasource;
import com.yao2san.simdif.entity.History;
import com.yao2san.simdif.entity.TableInfo;
import com.yao2san.simdif.enums.CommonStatus;
import com.yao2san.simdif.enums.Drivers;
import com.yao2san.simdif.mapper.DatasourceMapper;
import com.yao2san.simdif.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class DatasourceManageServiceImpl extends ServiceImpl<DatasourceMapper, Datasource> implements DatasourceManageService {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private TableInfoService tableInfoService;
    @Autowired
    private ColumnInfoService columnInfoService;
    @Autowired
    private HistoryService historyService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long add(DatasourceAddReq datasource) {
        //数据源类型
        String type = datasource.getType();
        Drivers drivers = Drivers.of(type);
        datasource.setDriverFile(drivers.getDriver());
        datasource.setDriverClassName(drivers.getDriverClassName());
        datasource.setStatus(CommonStatus.OK.getCode());
        datasource.setCreateDate(LocalDateTime.now());
        datasource.setUpdateDate(LocalDateTime.now());
        this.save(datasource);
        return datasource.getId();
    }

    @Override
    public PageInfo<DatasourceListRes> list(DatasourceListReq req) {
        List<DatasourceListRes> result = new ArrayList<>();
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<Datasource> query = Wrappers.lambdaQuery();
        query.eq(Datasource::getStatus, CommonStatus.OK.getCode());
        query.orderByDesc(Datasource::getCreateDate);
        List<Datasource> list = this.list(query);
        for (Datasource datasource : list) {
            DatasourceListRes res = new DatasourceListRes();
            BeanUtils.copyProperties(datasource, res);
            result.add(res);
        }
        return new PageInfo<>(result);
    }

    @Override
    public Datasource getDatasource(Long id) {
        Datasource datasource = this.getById(id);
        if (datasource == null) {
            throw new BusiException("数据源不存在");
        }
        return datasource;
    }

    @Override
    public void testConnection(DatasourceConnectionTestReq req) {
        DatasourceSyncService syncService = applicationContext.getBean(DefaultDatasourceSyncServiceImpl.class);
        syncService.test(req.getType(), req.getUrl(), req.getUsername(), req.getPassword());
    }

    @Override
    public void sync(DatasourceSyncReq req) {
        DatasourceSyncService syncService = applicationContext.getBean(DefaultDatasourceSyncServiceImpl.class);
        syncService.sync(req.getDatasourceId());
    }

    @Override
    public List<TableInfo> getTableInfos(Long datasourceId) {
        Datasource datasource = this.getDatasource(datasourceId);
        LambdaQueryWrapper<TableInfo> query = Wrappers.lambdaQuery();
        query.eq(TableInfo::getDatasourceId, datasourceId);
        query.eq(TableInfo::getSyncId, datasource.getSyncId());
        return tableInfoService.list(query);
    }

    @Override
    public List<ColumnInfo> getColumnInfos(Long datasourceId) {
        Datasource datasource = this.getDatasource(datasourceId);
        LambdaQueryWrapper<ColumnInfo> query = Wrappers.lambdaQuery();
        query.eq(ColumnInfo::getDatasourceId, datasourceId);
        query.eq(ColumnInfo::getSyncId, datasource.getSyncId());
        return columnInfoService.list(query);
    }

    @Override
    public void update(DatasourceUpdateReq req) {
        this.updateById(req);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(DatasourceDeleteReq req) {
        this.removeById(req.getId());
        LambdaQueryWrapper<TableInfo> tableQuery = Wrappers.lambdaQuery();
        tableQuery.eq(TableInfo::getDatasourceId, req.getId());
        tableInfoService.remove(tableQuery);
        LambdaQueryWrapper<ColumnInfo> columnQuery = Wrappers.lambdaQuery();
        columnQuery.eq(ColumnInfo::getDatasourceId, req.getId());
        columnInfoService.remove(columnQuery);
        LambdaQueryWrapper<History> historyQuery = Wrappers.lambdaQuery();
        historyQuery.or((q) -> {
            q.eq(History::getDs1Id, req.getId());
            q.eq(History::getDs2Id, req.getId());
        });
        historyService.remove(historyQuery);
    }
}
